package studio.raptor.dispatcher.server.handler.consumption;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import studio.raptor.databus.command.EventMetaData;
import studio.raptor.dispatcher.common.constant.EventStatus;
import studio.raptor.dispatcher.server.context.HandlerContext;
import studio.raptor.dispatcher.server.handler.Handler;
import studio.raptor.dispatcher.server.service.EventService;
import studio.raptor.dispatcher.server.service.SendService;

/**
 * 持久化消息
 *
 * @author jack
 * @since 1.0
 */
@Component
public class PersistEventHandler extends Handler {

  private static final Logger log = LoggerFactory.getLogger(PersistEventHandler.class);

  @Autowired
  EventService eventService;

  @Autowired
  SendService sendService;

  @Override
  public boolean process(HandlerContext context) {
    String code = context.getCode();
    Integer kindId = context.getKindId();
    Integer eventType = context.getEventType();
    EventMetaData metaData = context.getEvent().getEventMetaData();
    String objectKey = metaData.getBusinessNo();
    boolean result = eventService
        .saveEventTrace(context.getCode(), kindId, eventType, context.getTraceId(), metaData);
    if (result && context.isSort()) {
      result = getSuccessor().process(context);
      if (!result) {
        log.error("the event eventId：{} sort failed", objectKey);
        eventService.updateEventTrace(code, objectKey, kindId, EventStatus.SORT_FAILED, -1,
            "event sort error");
      }
    }

    if (!context.isSort()) {
      sendService.sendMessage(objectKey, code, kindId, eventType, false);
    }
    return result;
  }
}
